﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DDU.DataModel;
using System.Windows.Input;
using DDU.Library;

namespace DDU.ViewModel
{
    public class SemesterAddViewModel : MainViewModel
    {
        public SemesterAddViewModel()
        {
            SemesterToAdd.ValueChanged -= semesterToAdd_ValueChanged;
            SemesterToAdd.ValueChanged += semesterToAdd_ValueChanged;
        }

        void semesterToAdd_ValueChanged(object sender, PropertyArgs e)
        {
            RaisePropertyChanged(() => SemesterToAdd);
            RaisePropertyChanged(() => AddCommand);
        }

        private SemesterInfo semesterToAdd = new SemesterInfo();
        public SemesterInfo SemesterToAdd
        {
            get { return semesterToAdd; }
            set
            {
                semesterToAdd = value;
                RaisePropertyChanged(() => SemesterToAdd);
            }
        }

        private void Insert(SemesterInfo entity)
        {
            Database.CollectionOfSemesters.InsertOnSubmit(entity);
            Submit();
            SemesterToAdd = new SemesterInfo();
            RaisePropertyChanged(() => SemesterToAdd);
            RaisePropertyChanged(() => AddCommand);
        }

        public ICommand AddCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate {
                        int count = Database.CollectionOfSemesters.Count(s => s.Grade == SemesterToAdd.Grade && s.EducationLevel == SemesterToAdd.EducationLevel && s.Term == SemesterToAdd.Term);
                        return count == 0 && SemesterToAdd.EndTime > SemesterToAdd.StartTime;
                    },
                    ExecuteCallback = delegate
                    {
                        Insert(SemesterToAdd);
                    }
                };
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        if (BackUri != null)
                        {
                            Navigate(BackUri);
                        }
                    }
                };
            }
        }
    }
}
